#include "UploadConfig.h"

#include <QHostAddress>

#include "ConfigManager.h"
namespace Upload {

Configurer* Configurer::instance()
{
    static Configurer instance;
    return &instance;
}

Configurer::Configurer()
{
    if (!loadConfig()) {
        qWarning() << "加载IP配置失败,使用默认配置";
        defaultConfig();
    }
}
Configurer::~Configurer() {}
void Configurer::defaultConfig()
{
    m_configMap.clear();
    m_configMap["IP1"] = Config{"192.168.1.1", 8080, "1234567890", false};
    m_configMap["IP2"] = Config{"192.168.1.2", 8080, "1234567890", false};
    m_configMap["IP3"] = Config{"192.168.1.3", 8080, "1234567890", false};
    m_configMap["IP4"] = Config{"192.168.1.4", 8080, "1234567890", false};
}
bool Configurer::loadConfig()
{
    ConfigManager* configManager = ConfigManager::instance();
    configManager->loadConfig();
    m_configMap.clear();
    QJsonObject rootJsonObject = configManager->getSection("upload");
    if (rootJsonObject.isEmpty()) {
        return false;
    }
    for (auto it = rootJsonObject.begin(); it != rootJsonObject.end(); it++) {
        m_configMap[it.key()].IP = it.value().toObject()["IP"].toString();
        m_configMap[it.key()].port = it.value().toObject()["port"].toInt();
        m_configMap[it.key()].MN = it.value().toObject()["MN"].toString();
        m_configMap[it.key()].enabled = it.value().toObject()["enabled"].toBool();
    }
    return true;
}
bool Configurer::saveConfig()
{
    ConfigManager* configManager = ConfigManager::instance();
    QJsonObject rootJsonObject;
    for (auto it = m_configMap.begin(); it != m_configMap.end(); it++) {
        QJsonObject jsonObject;
        jsonObject["IP"] = it.value().IP;
        jsonObject["port"] = it.value().port;
        jsonObject["MN"] = it.value().MN;
        jsonObject["enabled"] = it.value().enabled;
        rootJsonObject[it.key()] = jsonObject;
    }
    configManager->setSection("upload", rootJsonObject);
    return configManager->saveConfig();
}
bool Configurer::setConfig(const QMap<QString, Config>& configMap)
{
    for (auto it = configMap.begin(); it != configMap.end(); it++) {
        // 判断IP是否合法
        if (!QHostAddress(it.value().IP).isNull()) {
            m_configMap[it.key()] = it.value();
        } else {
            qWarning() << "IP地址不合法" << it.value().IP;
            return false;
        }
    }
    return saveConfig();
}
}  // namespace Upload